package com.etoak.service.impl;

import cn.hutool.crypto.digest.MD5;
import com.etoak.common.constant.CommonConstant;
import com.etoak.common.jwt.JwtUtil;
import com.etoak.dto.LoginDTO;
import com.etoak.entity.User;
import com.etoak.mapper.UserMapper;
import com.etoak.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etoak.vo.TokenVO;
import com.etoak.web.exception.CustomException;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author et2403
 * @since 2024-08-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public TokenVO login(LoginDTO loginDTO) {

        String code = redisTemplate.opsForValue().get(CommonConstant.REDIS_KEY_CODE_PREFIX + loginDTO.getUuid());
        if (StringUtils.isEmpty(code) || !StringUtils.equals(code, loginDTO.getCode())) {
            throw new CustomException("验证码错误或失效");
        }
        User user = lambdaQuery()
                .eq(User::getUsername, loginDTO.getUsername())
                .eq(User::getPassword, MD5.create().digestHex(loginDTO.getPassword()))
                .one();
        if (ObjectUtils.isEmpty(user)) {
            throw new CustomException("用户名或密码错误");
        }

        // 生成nwt
        Map<String, Object> map = new HashMap<>();
        map.put("id", user.getId());
        map.put("username", user.getUsername());
        String token = JwtUtil.create(map);
        return new TokenVO(user.getUsername(), token);

    }
}
